<template>
  <div class="menu-list">
    <div style="margin-bottom: 12px;">
      <a-button @click="handleRootAddClick">新增菜单</a-button>
    </div>
    <cg-table
      :default-expand-all-rows="true"
      :show-all-list="true"
      :show-button="false"
      :show-row-selection="false"
      :get-list="getList"
      :table-header="columns"
    >
      <span slot="menuType" slot-scope="text">
        <template v-if="text === '1'">Folder</template>
        <template v-else-if="text === '2'">Menu</template>
        <template v-else>Button</template>
      </span>
      <div slot="operator" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          @click="handleItemAddClick(record)"
          v-if="record.menuType !== '3'"
        >
          新增
        </a-button>
        <a-button size="small" type="link" @click="handleItemEditClick(record)">
          编辑
        </a-button>
        <a-button size="small" type="link" @click="handleItemDeleteClick(record)">
          删除
        </a-button>
      </div>
    </cg-table>
    <menu-modal :modal-data="modalData" />
  </div>
</template>

<script>
import CgTable from '@/components/cgTable/index.jsx';
import MenuModal from '@/views/menuList/components/MenuModal';
import menuApi from '@/api/menu';
import { columns, addEditFormData } from '@/mock/menuList';
import emitter from '@/utils/emitter';
import Events from '@/utils/event';
import { noop } from 'lodash-es';

export default {
  name: 'MenuList',
  components: {
    CgTable,
    MenuModal
  },
  data () {
    return {
      modalData: {
        record: {},
        type: ''
      },
      getList: menuApi.list,
      columns,
      addEditFormData
    };
  },
  methods: {
    handleRootAddClick () {
      this.modalData = {
        record: {},
        type: 'ADD'
      };
    },
    handleItemAddClick (record) {
      this.modalData = {
        record,
        type: 'ADD'
      };
    },
    handleItemEditClick (record) {
      this.modalData = {
        record,
        type: 'EDIT'
      };
    },
    handleItemDeleteClick ({ id }) {
      this.$confirm({
        title: '提示',
        content: '确定要删除吗?',
        onOk: () => {
          menuApi.delete({ id }).then(res => {
            this.$message.success(res.msg);
            emitter.emit(Events.REFRESH_TABLE, false);
          }).catch(() => {
            this.$message.error('删除失败');
          });
        },
        onCancel: noop
      });
    }
  },
  created () {
    emitter.on(Events.SHOW_ADD_EDIT_MODAL, this.showModal);
  }
};
</script>

<style scoped>

</style>
